package server.java.autoduel.Cars;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import server.java.autoduel.Util.XmlFileFilter;

import com.thoughtworks.xstream.XStream;

/**
 * Provides a set of chassis blueprints for the game to work with
 * 
 * @author Ian Axelrod
 * @author Liz Ha
 * @author Andrew Muldowney
 * @author Edward Futch
 * @version %I%, %G%
 */
public class ChassisFactory {

	/**
	 * The data directory chassis xml files are present in
	 */
	private final static String data_dir = "/data/chasses/";

	/**
	 * A hash map of all the chasses, keyed by their name
	 */
	private static HashMap<String, Chassis> chasses;

	/**
	 * Loads up all the chassis data from the server filesystem
	 * 
	 * @throws IOException
	 */
	public static void loadChassis(String currentDir) throws IOException {
		final File dir = new File(currentDir + ChassisFactory.data_dir);
		final File[] files = dir.listFiles(new XmlFileFilter());
		ChassisFactory.chasses = new HashMap<String, Chassis>();

		for (final File file : files) {
			final FileInputStream reader = new FileInputStream(file);
			final byte[] buf = new byte[(int) file.length()];

			reader.read(buf);
			reader.close();
			final XStream xstream = new XStream();
			xstream.alias("Chassis", Chassis.class);
			final Chassis chassis = (Chassis) xstream.fromXML(new String(buf));
			ChassisFactory.chasses.put(chassis.getName(), chassis);
		}
	}

	/**
	 * Provides to the caller a copy of the internal list of chasses available
	 * 
	 * @return the chasses available in this factory
	 */
	public static ArrayList<Chassis> provideChasses() {
		final ArrayList<Chassis> chassesCopy = new ArrayList<Chassis>();

		for (final Chassis chassis : ChassisFactory.chasses.values()) {
			chassesCopy.add(chassis.copy());
		}
		return chassesCopy;
	}

	/**
	 * Provides the requested chassis to the caller
	 * 
	 * @param name
	 *            the name of the chassis to create
	 * @return a copy of the requested chassis
	 */
	public static Chassis provideChassis(String name) {
		return ChassisFactory.chasses.get(name).copy();
	}
}